import { defineComponent, PropType, ref } from 'vue'
import { usePrefix } from '../../hooks'
import { IconWidget } from '../IconWidget'
import { TextWidget } from '../TextWidget'
import {
  IResourceLike,
  isResourceList,
  isResourceHost,
  IResource,
} from '@/core'
import cls from 'classnames'

import './styles.less'

export const ResourceWidget = defineComponent({
  props: {
    title: {
      type: String,
      required: true,
    },
    sources: {
      type: Array as PropType<IResourceLike[]>,
    },
    defaultExpand: {
      type: Boolean,
      default: true,
    },
  },
  setup(props) {
    const prefix = usePrefix('resource')

    const expand = ref(props.defaultExpand)

    const sources = (props.sources as IResourceLike[]).reduce<IResource[]>(
      (buf, source) => {
        if (isResourceList(source)) {
          return buf.concat(source)
        } else if (isResourceHost(source)) {
          return buf.concat(source.Resource)
        }
        return buf
      },
      [],
    )
    const remainItems =
      sources.reduce((length, source) => {
        return length + (source.span ?? 1)
      }, 0) % 3

    const renderSource = () =>
      sources.map((source) => {
        const { node, icon, title, thumb, span } = source

        return (
          <div
            class={prefix + '-item'}
            style={{ gridColumnStart: `span ${span || 1}` }}
            key={node.id}
            data-designer-source-id={node.id}
          >
            {thumb && <img class={prefix + '-item-thumb'} src={thumb} />}
            {icon && (
              <IconWidget
                class={prefix + '-item-icon'}
                infer={icon}
                style={{ width: 150, height: 40 }}
              />
            )}
            <span class={prefix + '-item-text'}>
              {<TextWidget title={title}></TextWidget>}
            </span>
          </div>
        )
      })

    return () => (
      <div class={cls(prefix, { expand: expand.value })}>
        <div
          class={prefix + '-header'}
          onClick={(e) => {
            e.stopPropagation()
            e.preventDefault()
            expand.value = !expand.value
          }}
        >
          <div class={prefix + '-header-expand'}>
            <IconWidget infer="Expand" size={12} />
          </div>
          <div class={prefix + '-header-content'}>
            <TextWidget title={props.title}></TextWidget>
          </div>
        </div>
        <div class={prefix + '-content-wrapper'}>
          <div class={prefix + '-content'}>
            {renderSource()}
            {remainItems ? (
              <div
                class={prefix + '-item-remain'}
                style={{ gridColumnStart: `span ${3 - remainItems}` }}
              ></div>
            ) : null}
          </div>
        </div>
      </div>
    )
  },
})
